package com.globalwave.eps.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.globalwave.base.BaseAction;
import com.globalwave.common.ArrayPageList;
import com.globalwave.common.Convertor;
import com.globalwave.common.cache.CodeHelper;
import com.globalwave.eps.entity.ElectricityProject;
import com.globalwave.eps.entity.ElectricityProjectCriterion;
import com.globalwave.eps.entity.ElectricityProjectLine;
import com.globalwave.eps.service.ElectricityProjectService;
import com.globalwave.report.template.excel.ExcelTemplate;
import com.globalwave.system.web.annotations.Pid;
import com.opensymphony.xwork2.Preparable;

@Service("eps_electricityProjectAction")
@Scope("prototype")
public class ElectricityProjectAction extends BaseAction implements Preparable {

    private static final long serialVersionUID = 8582051849254108462L;
    
    private ElectricityProjectService electricityProjectService ;
    private ElectricityProject electricityProject ;
    private ElectricityProjectCriterion criterion ; 

    
    public String execute() throws Exception {    
        return this.list();    
    }
    
    @Pid(value=9001)
    public String list() throws Exception {      
        
        ArrayPageList<ElectricityProject> pageList = 
            electricityProjectService.query(criterion,pageIndex,pageSize,null) ;

        renderXML(pageList.asXML()) ;
        
        return null ;    
        
    }

    @Pid(value=9009)
    public String report() throws Exception {      
        
        ArrayPageList<Object> pageList = 
            electricityProjectService.report(criterion,pageIndex,pageSize,null) ;

        renderXML(pageList.asXML()) ;
        
        return null ;    
        
    }
    @Pid(value=9009)
    public String export() throws Exception {      
        ArrayPageList<Object> pageList = 
            electricityProjectService.report(criterion,1,Integer.MAX_VALUE,null) ;


		ExcelTemplate template = new ExcelTemplate("com/globalwave/eps/template/projects.xls") ;
		
		template.load() ;
		
		Map<String, Object> context = new HashMap<String, Object>() ;

		context.put("u", this.getSessionUser()) ;
		context.put("l", pageList) ;

		template.compile(context) ;
		
        HttpServletResponse resp = this.getResponse() ;
        
        resp.setContentType("application/octet-stream");
        // resp.setContentLength( (int)f.length() );
        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + System.currentTimeMillis() + ".xls\"" );
	
		template.saveTo(resp.getOutputStream()) ;

        //template.saveTo(new FileOutputStream("d:\\temp\\result_test2.xls", false));
        
        return null ;
    }

    @Pid(value=9002)
    public String create()  throws Exception {              
        
        electricityProject.setLines((List)Convertor.xml2List(super.getParamsAsXml(), ElectricityProjectLine.class));
        
        Object newElectricityProject = electricityProjectService.create(electricityProject) ;

        renderXML(this.getSuccessCreateMessage(newElectricityProject).asXML()) ;
        
        return null;    
        
    }

    

    @Pid(value=9002)
    public String copy()  throws Exception {              
        
        Object newElectricityProject = electricityProjectService.copy(electricityProject) ;

        renderXML(this.getSuccessCreateMessage(newElectricityProject).asXML()) ;
        
        return null;    
        
    }
    

    @Pid(value=9003)
    public String update()  throws Exception {     
        
    	if (!StringUtils.isEmpty(super.getParamsAsXml())) {
            electricityProject.setLines(
            		(List)Convertor.xml2List(super.getParamsAsXml(), ElectricityProjectLine.class));
    	}
    	
        electricityProjectService.update(electricityProject) ;

        renderXML(this.getSuccessUpdateMessage(electricityProject).asXML()) ;
        
        return null;    
        
    }

    @Pid(value=9004)
    public String delete()  throws Exception {
        if (ids == null) { 
            electricityProjectService.delete(electricityProject) ;
        } else {
            electricityProjectService.deleteAll(ids) ;
        }

        renderXML(this.getSuccessDeleteMessage().asXML()) ;
        
        return null;    
        
    }    

    @Pid(value=9000)
    public String get()  throws Exception {
    	
    	Element result = this.getProjectMessage(
        		electricityProjectService.getWithLines(electricityProject), "") ;
    	
        renderXML(addBudgetStaffOptions(result).asXML()) ;
        
    	return null ;
    }

    @Pid(value=Pid.DO_NOT_CHECK)
    public String getOptions() throws Exception {
        renderXML(addBudgetStaffOptions(null).asXML()) ;
    	return null ;
    }
    
    private Element addBudgetStaffOptions(Element root) throws Exception {
    	if (root == null) {
    	    Document document = DocumentHelper.createDocument();
            document.setXMLEncoding("UTF-8");
            root = document.addElement("root") ;
    	}
    	
    	root.add(Convertor.list2Xml(electricityProjectService.getBudgetStaffOptions(), "BudgetStaffOptions")) ;
    	
    	return root ;
    }
    
    
    private Element getProjectMessage(ElectricityProject project, String msg) throws Exception {

        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding("UTF-8");
        Element root = document.addElement("root") ;
        root.addElement("message").addText(msg) ;
        
        if (project != null) {
        	Element eOrder = Convertor.object2Xml(project) ;
        	if (project.getLines() != null) {
        	    eOrder.add(Convertor.list2Xml(project.getLines(), "lines")) ;
        	}
        	root.addElement("data").add(eOrder);
        }
        
        root.addElement("versionId").addText(String.valueOf(CodeHelper.getVersionId())) ;
        
        return root ;
             
    }
    
    public void prepare() throws Exception {
        // Auto-generated method stub , donothing
        
    }
    
    public void setElectricityProjectService(ElectricityProjectService electricityProjectService) {
        this.electricityProjectService = electricityProjectService;
    }

    public ElectricityProject getElectricityProject() {
        return electricityProject;
    }

    public void setElectricityProject(ElectricityProject electricityProject) {
        this.electricityProject = electricityProject;
    }

    public ElectricityProjectCriterion getCriterion() {
        return criterion;
    }

    public void setCriterion(ElectricityProjectCriterion criterion) {
        this.criterion = criterion;
    }

}
